package raft

// need hold rf.mu before call this func
func (rf *Raft) getsm() sminterface {
	switch rf.currentState {
	case FollowerState:
		return rf.follower
	case LeaderState:
		return rf.leader
	case CandidateState:
		return rf.candidate
	}
	return nil
}

// need hold rf.mu before call this func
func (rf *Raft) changeToState(state State, newTerm int) {
	//sameAsBefore := rf.currentState == state
	rf.Log("TERM", "new state is %s, new Term is %d", State2Str[state], newTerm)
	sameState := rf.currentState == state
	sameTerm := rf.persistentContext.CurrentTerm == newTerm
	if sameTerm && !(!sameState && state == LeaderState) {
		rf.Log("WARN", "change state without changing term")
	}
	oldstate := rf.currentState

	rf.currentState = state
	rf.WriteTerm(newTerm)

	if !sameTerm {
		rf.WriteVoted(-1)
	}

	rf.getsm().enter(oldstate, !sameTerm)
}
